package com.wufun.overseas.main.activity;

import android.content.Intent;
import android.graphics.drawable.TransitionDrawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.TextView;

import com.papa.controller.core.PadKeyEvent;
import com.papa.controller.core.PadMotionEvent;
import com.wufun.overseas.R;
import com.wufun.overseas.joystick.map.BlackListManager;
import com.wufun.overseas.joystick.map.HandShankUtil;
import com.wufun.overseas.joystick.map.KeyMapManager;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by caowd on 2015/6/12.
 * 手柄按钮设置
 */
public class HandShankCheckKeyActivity extends HandShankBaseActivity {

    private boolean            isKeyDown;
    private SoundPool          soundPool;
    private TransitionDrawable transition;
    private HashMap<Integer, KeyInfo> map = new HashMap<Integer, KeyInfo>();


    private HashMap<String, Integer> keyMap = new HashMap<String, Integer>();
    //判断是否是从无蓝牙记录页进入
//    @Extra
    String from;

    @Bind(R.id.titleText)
    TextView titleText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.handshank_check_key);
        ButterKnife.bind(this);

        if (getIntent() != null)
            from = getIntent().getStringExtra("from");

        afterView();
    }

    private void loadSound() {
        soundPool = new SoundPool(21, AudioManager.STREAM_MUSIC, 10);
        soundPool.load(this, R.raw.jiejitoubi, 1);
    }

    private void playBtnSound() {
        soundPool.play(1, 1, 1, 1, 0, 1f);
    }


    @OnClick(R.id.backImage)
    void backImage() {
        if (TextUtils.isEmpty(from)) {
            finish();
        } else {
            if (from.equals("first")) {
                Intent intent = new Intent(this, com.wufun.overseas.main.activity.HandShankYesActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
                finish();
            }
        }

    }

    @OnClick(R.id.okButn)
    void okButn() {
        Intent intent = new Intent(this, com.wufun.overseas.main.activity.HandShankYesActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        startActivity(intent);
        finish();
    }

    @OnClick(R.id.errButn)
    void errButn() {
        Intent intent = new Intent(this, com.wufun.overseas.main.activity.HandShankSetKeyActivity.class);
        if (!TextUtils.isEmpty(from)) {
            intent.putExtra("from", from);
            startActivity(intent);
            finish();
        } else {
            startActivity(intent);
        }

    }

    void afterView() {

        loadSound();


        initViews();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initMap();
    }


    private void initViews() {
        findViewById(R.id.handshank_check_layout).requestFocus();
        titleText.setText(getResources().getString(R.string.gamepad_check_key));
    }

    private void initMap() {
        keyMap.clear();
        Map      map      = KeyMapManager.getMap("KEY");
        Set      set      = map.keySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            String name = (String) iterator.next();
            String key  = (String) map.get(name);
            keyMap.put(name, Integer.parseInt(key));
        }

        if (keyMap.size() == 0) {
            keyMap.put(HandShankUtil.KEY_START, 108);
            keyMap.put(HandShankUtil.KEY_SELECT, 109);
            keyMap.put(HandShankUtil.KEY_X, 99);
            keyMap.put(HandShankUtil.KEY_A, 96);
            keyMap.put(HandShankUtil.KEY_Y, 100);
            keyMap.put(HandShankUtil.KEY_B, 97);
            keyMap.put(HandShankUtil.KEY_L1, 102);
            keyMap.put(HandShankUtil.KEY_L2, 104);
            keyMap.put(HandShankUtil.KEY_R1, 103);
            keyMap.put(HandShankUtil.KEY_R2, 105);

            keyMap.put(HandShankUtil.KEY_DPAD_LEFT, 21);
            keyMap.put(HandShankUtil.KEY_DPAD_UP, 19);
            keyMap.put(HandShankUtil.KEY_DPAD_RIGHT, 22);
            keyMap.put(HandShankUtil.KEY_DPAD_DOWN, 20);

            keyMap.put(HandShankUtil.KEY_BUTTON_THUMBR, 107);

            keyMap.put(HandShankUtil.KEY_BUTTON_THUMBL, 106);
        }

        initMapData(keyMap);
    }


    private void initMapData(Map<String, Integer> keyMap) {
        map.clear();
        map.put(keyMap.get(HandShankUtil.KEY_Y), new KeyInfo(R.id.y, R.drawable.handshank_check_point_normal, R.drawable.handshank_check_point_pressed));
        map.put(keyMap.get(HandShankUtil.KEY_A), new KeyInfo(R.id.a, R.drawable.handshank_check_point_normal, R.drawable.handshank_check_point_pressed));
        map.put(keyMap.get(HandShankUtil.KEY_X), new KeyInfo(R.id.x, R.drawable.handshank_check_point_normal, R.drawable.handshank_check_point_pressed));
        map.put(keyMap.get(HandShankUtil.KEY_B), new KeyInfo(R.id.b, R.drawable.handshank_check_point_normal, R.drawable.handshank_check_point_pressed));
        map.put(keyMap.get(HandShankUtil.KEY_L1), new KeyInfo(R.id.handshank_check_lb, R.drawable.handshank_check_lb_normal, R.drawable.handshank_check_lb_pressed));
        map.put(keyMap.get(HandShankUtil.KEY_L2), new KeyInfo(R.id.handshank_check_ls, R.drawable.handshank_check_ls_normal, R.drawable.handshank_check_ls_pressed));
        map.put(keyMap.get(HandShankUtil.KEY_R1), new KeyInfo(R.id.handshank_check_rb, R.drawable.handshank_check_rb_normal, R.drawable.handshank_check_rb_pressed));
        map.put(keyMap.get(HandShankUtil.KEY_R2), new KeyInfo(R.id.handshank_check_rs, R.drawable.handshank_check_rs_normal, R.drawable.handshank_check_rs_pressed));

        map.put(keyMap.get(HandShankUtil.KEY_BUTTON_THUMBL), new KeyInfo(R.id.handshank_check_stick_l, R.drawable.handshank_check_stick_normal, R.drawable.handshank_check_stick_pressed));
        map.put(keyMap.get(HandShankUtil.KEY_BUTTON_THUMBR), new KeyInfo(R.id.handshank_check_stick_r, R.drawable.handshank_check_stick_normal, R.drawable.handshank_check_stick_pressed));

        map.put(keyMap.get(HandShankUtil.KEY_DPAD_LEFT), new KeyInfo(R.id.handshank_check_cross, R.drawable.handshank_check_cross_bg, R.drawable.handshank_check_cross_left));
        map.put(keyMap.get(HandShankUtil.KEY_DPAD_UP), new KeyInfo(R.id.handshank_check_cross, R.drawable.handshank_check_cross_bg, R.drawable.handshank_check_cross_top));
        map.put(keyMap.get(HandShankUtil.KEY_DPAD_RIGHT), new KeyInfo(R.id.handshank_check_cross, R.drawable.handshank_check_cross_bg, R.drawable.handshank_check_cross_right));
        map.put(keyMap.get(HandShankUtil.KEY_DPAD_DOWN), new KeyInfo(R.id.handshank_check_cross, R.drawable.handshank_check_cross_bg, R.drawable.handshank_check_cross_down));

    }

    @Override
    protected boolean onKeyEvent(int keyCode, PadKeyEvent event) {
        String deviceName = event.getName();
        if (BlackListManager.getInstance().isInBlackList(deviceName)) return false;

        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            onKeyDown1(keyCode, padEvent2KeyEvent(event));
        } else {
            onKeyUp1(keyCode, padEvent2KeyEvent(event));
        }

        return super.onKeyEvent(keyCode, event);
    }

    @Override
    protected boolean onStickEvent(PadMotionEvent event) {
        return super.onStickEvent(event);
    }

    public boolean onKeyUp1(int keyCode, KeyEvent event) {
        String deviceName = event.getDevice().getName();
        if (BlackListManager.getInstance().isInBlackList(deviceName)) return false;

        if (keyCode != KeyEvent.KEYCODE_BACK) {
            KeyInfo keyInfo = map.get(keyCode);
//            if (keyInfo != null) {
//                ImageView imageView = (ImageView) findViewById(keyInfo.id);
//                imageView.setImageResource(keyInfo.normal_drawable);
//                isKeyDown = false;
//            }
            handleKeyUpUi(keyInfo);
            return true;
        }

        return super.onKeyUp(keyCode, event);
    }

    Handler mHandler = new Handler();

    void handleKeyDownUi(final KeyInfo keyInfo) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (keyInfo != null) {
                    playBtnSound();
                    ImageView imageView = (ImageView) findViewById(keyInfo.id);
                    imageView.setImageResource(keyInfo.pressed_drawable);
                    imageView.invalidate();
                }
            }
        });
    }

    void handleKeyUpUi(final KeyInfo keyInfo) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (keyInfo != null) {
                    ImageView imageView = (ImageView) findViewById(keyInfo.id);
                    imageView.setImageResource(keyInfo.normal_drawable);
                    imageView.invalidate();
                    isKeyDown = false;
                }
            }
        });
    }

    public boolean onKeyDown1(int keyCode, KeyEvent event) {
        try {
            String deviceName = event.getDevice().getName();
            if (BlackListManager.getInstance().isInBlackList(deviceName)) return false;

            adjustVolume(event);

            if (keyCode != KeyEvent.KEYCODE_BACK) {
                if (!isKeyDown) {
                    isKeyDown = true;
                    KeyInfo keyInfo = map.get(keyCode);
                    handleKeyDownUi(keyInfo);
                }
                return true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.onKeyDown(keyCode, event);

    }

    private void adjustVolume(KeyEvent event) {
        int          keyCode       = event.getKeyCode();
        AudioManager mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        switch (keyCode) {

            case KeyEvent.KEYCODE_VOLUME_UP:
                mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                        AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND
                                | AudioManager.FLAG_SHOW_UI);
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                        AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND
                                | AudioManager.FLAG_SHOW_UI);
                break;

            default:
                break;
        }
    }

    private class KeyInfo {
        public int id;
        public int normal_drawable;
        public int pressed_drawable;

        public KeyInfo(int id, int normal_drawable, int pressed_drawable) {
            this.id = id;
            this.normal_drawable = normal_drawable;
            this.pressed_drawable = pressed_drawable;
        }
    }
}
